<!--
 * @Author: your name
 * @Date: 2021-02-05 14:52:13
 * @LastEditTime: 2021-03-29 11:32:11
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue3-element-admin\src\views\layoutpages\system\Roles.vue
-->
<template>
  <div class="ve_container">
    <RoleHeader>
            <div style=" margin-top: 10px;" @click="addRole">
                        <el-button type="danger" icon="ArrowLeft" size="mini"
                        >+ 新增</el-button>
                    </div>
    </RoleHeader>
    <!-- 搜索
            -->

    <!-- table工具条 -->
    <!--<el-row ref="toolBar" class="ve_header_row_class_name ve_p_10">
            <el-button
                v-permission="['add']"
                size="mini"
                type="primary"
                @click="handleEdit(menus.add.name)"
                >{{ menus.add.name }}</el-button
            >
        </el-row>-->
    <div>
      <div class="tab">
        <el-row>
          <el-col :span="5">
            <div class="tab-k">角色id</div>
          </el-col>
          <el-col :span="5">
            <div class="tab-k">角色名称</div>
          </el-col>
          <el-col :span="5">
            <div class="tab-k">排序</div>
          </el-col>
          <el-col :span="5">
            <div class="tab-k">添加时间</div>
          </el-col>
          <el-col :span="2">
            <div class="tab-k">操作</div>
          </el-col>
        </el-row>
      </div>
      <div class="tab-value">
        <div class="d" v-for="(item, index) in  state.tableData" :key="index">
          <el-row>
            <el-col :span="5">
              <div class="tab-v fnt">{{item.id}}</div>
            </el-col>
            <el-col :span="5">
              <div class="tab-v">{{item.name}}</div>
            </el-col>
            <el-col :span="5">
                <div class="tab-v">{{item.pid}}</div>
            </el-col>
            <el-col :span="5">
                <div class="tab-v">{{item.createtime}}</div>
            </el-col>
            <el-col :span="2" v-if="item.name!=='超级管理员'">
              <div class="tab-v d-fix">
                <div class="butt-edit" style="margin-right:10px;">
                  <el-button size="mini" type="primary" @click="editRole(item.id)">编辑</el-button>
                </div>
                <div class="butt-edit">
                  <el-button size="mini" type="danger" @click="delGroup(item.id)">删除</el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="pagin">
          <!-- 分页 -->
           <el-pagination v-if="tableData.length && total>params.limit" layout="prev, pager, next"  
                        @current-change="handleCurrentChange"
                        :current-page="params.page"
                        :page-size="params.limit" 
                        :total="total">
            </el-pagination>
        </div>
      </div>
     

      <el-dialog
      :title="state.titleText+'角色'"
      v-model="state.dialogVisible"
      custom-class="dialog"
      :append-to-body="true"
      
    >
      <el-form
        :model="state.form"
        label-width="80px"
        hide-required-asterisk
        class="form"
      >
        <el-form-item label="角色名称:" required>
          <el-input v-model="state.form.name" autocomplete="off"></el-input>
        </el-form-item>

        <!-- <el-form-item label="上级角色:">
          <el-select v-model="state.form.region" placeholder="请选择角色">
            <el-option :label="item.name" :value="item.pid" v-for="item in state.tableData" :key="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <div class="tree">
          <div class="title">菜单权限:</div>
          <div class="tree-list">
            <el-tree
              :data="state.JurisdictionMenuArr"
              show-checkbox
              node-key="id"
              :default-checked-keys="state.defaultCheckedKeys"
              ref="tree"
            >
            </el-tree>
            <div class="info">设置该角色有权操作的功能</div>
          </div>
        </div>

        <!-- <el-form-item label="排序:" required>
          <el-input v-model="state.form.sott" autocomplete="off"></el-input>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="comfirmBtn">确 定</el-button>
        </span>
      </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// import RoleEdit from "./components/RoleEdit";
import RoleHeader from "@/components/common/role-header";
import {
  reactive,
  toRefs,
  computed,
  ref,
  onMounted,
  getCurrentInstance,
  nextTick
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { findName } from "../common";
import {roleList,jurisdictionMenu,addRoleApi,editRoleApi,RoleDetailApi,delRoleApi } from "@/request/api"


//*导入公共查询方法
import {
  onSubmit,
  resetForm,
  handleSizeChange,
  // handleCurrentChange,
  rowClassName,
  cellClassName,
  rowClick,
  maxHeight
} from "@/views/layoutpages/common";

const state = reactive({
    form:{
        name:'',
        id:'',
    },
    dialogVisible: false,
    titleText:'',
    tableData:'',
    total:'',
    JurisdictionMenuArr:'',
    defaultCheckedKeys:[],
})

export default {
  data: () => ({
    description: "角色信息查询与设置",
    menus: {
      search: { name: "查询" },
      add: { name: "添加" },
      edit: { name: "编辑" },
      del: { name: "删除" },
      member: { name: "查看成员", toPath: true }
    }
  }),
  components: {
    // RoleEdit,
    RoleHeader
  },
  setup() {
    const dialogVisible = ref(false)
    const { proxy } = getCurrentInstance();
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    const menuList = computed(() => store.getters.menuList).value;
    const value1 = true
    const rowData = ref(null);
    const dialogTitle = ref("");
    const showDialog = ref(false);
    const ve_max_height = ref(0);
    const ve_rowIndex = ref(null);
    const toolBar = ref(null);
    const pagination = ref(null);
    const queryForm = ref(null);
    const tableData = ref([]);
    const params = reactive({
      name: "",
      limit: 10,
      page: 1,
      total: 50
    });
    const { name, limit, page, total } = toRefs(params);

    /**
     * @description:添加or编辑事件
     * @param {*}
     * @return {*}
     */
    const handleEdit = (title, row = null) => {
      showDialog.value = true;
      dialogTitle.value = title;
      rowData.value = row;
    };
    /**
     * @description: dialog事件
     * @param {*}
     * @return {*}
     */
    const handelDialog = e => {
      showDialog.value = e;
      getDataList();
    };
    /**删除行数据
     * @description:
     * @param {*}
     * @return {*}
     */
    const handleDel = id => {
      proxy
        .$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error"
        })
        .then(async () => {
          const { code } = await VE_API.system.roleDel({ id });
          if (code == "00") {
            getDataList();
          }
        })
        .catch(() => {
          proxy.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    };
    /**
     * @description:查看成员
     * @param {*}
     * @return {*}
     */
    const allMember = id => {
      // 获取当前path的id
      let pathId = route.name.slice(route.name.lastIndexOf("-") + 1);
      // 获取要跳转到的路由
      const toName = findName(
        "member",
        "system/Users",
        pathId,
        menuList,
        proxy
      );
      router.push({ name: toName, query: { id } });
    };
    /**
     * @description: 获取列表数据
     * @param {*}
     * @return {*}
     */
    const getDataList = async () => {
      roleList().then(res=>{
          if (res.ret == 200) {
            state.tableData = res.data.data
            state.total = res.data.total
          }
      })
     
    };
    function getJurisdictionMenu(){
      jurisdictionMenu().then(res=>{
           if (res.ret == 200) {
            let powerData = res.data.admin_roles;
            let newPowerData = [];
            for (const key in powerData) {
              newPowerData.push(powerData[key]);
            }
            state.JurisdictionMenuArr = newPowerData;
          }
      })
    }
    const handleCurrentChange = (val) => {
                console.log(val);
        if (val !== params.page) {
            params.page = val
            return getDataList()
        }
    }

    function addRole(){
      state.titleText = '新增'
      state.dialogVisible = true
      state.defaultCheckedKeys = []
      state.form.name = ''
      state.form.id = ''
    }
    function editRole(group_id){
        state.titleText = '编辑'
        state.dialogVisible = true
        proxy.$nextTick(()=>{
            proxy.$refs.tree.setCheckedNodes([])
        })
        state.form.name = ''
        state.form.id = ''
      RoleDetailApi({ group_id}).then(res=>{
        state.defaultCheckedKeys = []
        if (res.ret == 200) {
            state.form.name = res.data.group.name;
            state.form.id = res.data.group.id;
            if (res.data.group.rules && res.data.group.rules.length) {
              state.defaultCheckedKeys = res.data.group.rules.split(",");
            }
          }
      
      })

      
    }

    function comfirmBtn(){
      if (!state.form.name) {
        return proxy.$message.error('请先输入角色名称')
      }
       let data ={
           rules : proxy.$refs.tree.getCheckedKeys().join(','),
           name : state.form.name,
           status : 1,
        }
      if (state.titleText == '新增') {
        addRoleApi(data).then(res=>{
            if (res.ret == 200) {
            proxy.$message.success('添加成功');
            state.form.name = "";
            getDataList();
            state.dialogVisible = false;
          }
        })
      } else if(state.titleText == '编辑') {
         data.group_id = state.form.id
         editRoleApi(data).then(res=>{
            if (res.ret == 200) {
            proxy.$message.success('编辑成功');
            state.form.name = "";
            getDataList();
            state.dialogVisible = false;
          }
        })
      }
    }

     //删除接口
    const delGroup = (group_id) => {
       proxy.$messageBox.confirm("确认后将无法恢复", "您确定要删除该记录吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
            delRoleApi({group_id})
              .then((res) => {
                if (res.ret == 200) {
                  proxy.$message.success({
                    message: "删除成功",
                  });
                  getDataList();
                } else {
                  proxy.$message.error({
                    message: res.msg,
                  });
                }
              });
        })
        .catch(() => {
           proxy.$message({
            type: "info",
            message: "已取消删除",
          });
        });



     
    };

    onMounted(async () => {
      await getDataList();
      await getJurisdictionMenu();
      maxHeight(pagination, queryForm, toolBar, ve_max_height);
    });
    return {
      dialogVisible,
      ve_max_height,
      ve_rowIndex,
      getDataList,
      tableData,
      params,
      ...{ name, limit, page, total },
      ...{ pagination, queryForm, toolBar },
      ...{ handleEdit, rowData, dialogTitle, showDialog },
      ...{
        onSubmit,
        resetForm,
        handleSizeChange,
        rowClassName,
        cellClassName,
        rowClick,
        maxHeight
      },
      handelDialog,
      handleDel,
      allMember,
      value1,
      state,
      handleCurrentChange,
      addRole,
      editRole,
      comfirmBtn,
      delGroup,
    };
  }
};
</script>

<style lang="scss" scoped>
.el-main {
  background: #eff3fb !important;
}
.bg {
  background: white;
  padding: 55px 30px 35px 35px;
  border-radius: 10px;
}
.tab {
  margin-top: 20px;
  margin-bottom: 20px;
  padding-left: 20px;
}
.tab-value {
  background: white;
  padding-left: 20px;
  padding-top: 5px;
  border-radius: 8px;
  min-height: 400px;
  position: relative;
  padding-bottom: 80px;
}
.tab-k {
  color: #7a8499;
  font-size: 13px;
  font-weight: 600;
}
.tab-v {
  color: #7a8499;
  font-size: 13px;
  line-height: 30px;
}
.fnt {
  color: #45484d;
  font-weight: bold;
}
.d {
  padding-top: 10px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f9f9f9;
}
.d-fix {
  display: flex;
  justify-content: space-between;
}
.pagin {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  margin: auto;
  text-align: center;
}

 .el-overlay {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
  .el-form {
    width: 50%;
    margin: 0 auto;
    .el-select {
      width: 100%;
    }
  }
  .tree {
    display: flex;
    margin: 24px 0;
    .title {
      padding-right: 10px;
      margin-left: 14px;
    }
    .info {
      clear: both;
      min-height: 22px;
      color: rgba(0, 0, 0, 0.45);
      font-size: 13px;
      margin-top: 10px;
    }
  }
}
</style>
